
export default {
	state:{
		list:[],
		// 选中列表（存放选中的id）
		selectedList:[],
		
	},
	getters:{
		// 判断是否全选
		checkedAll:(state)=>{
			return state.list.length === state.selectedList.length
		},
		// 合计
		totalPrice:(state)=>{
			var total = 0
			state.list.forEach(v=>{
				if (state.selectedList.indexOf(v.cart_id) > -1) {
					total += v.price*100*v.goods_num
				}
			})
			return (total/100).toFixed(2)
		},
		// 禁用全选
		disableSelectAll:(state)=>{
			return state.list.length === 0
		},
		// 购物车商品数量
		cartCount:(state)=>{
			if(state.list.length <= 99){
				return state.list.length
			}
			return '99+'
		}
	},
	mutations:{
		// 初始化list
		initCartList(state,list){
			state.list = list
			state.selectedList = []
		},
		// 选中/取消选中某个商品
		selectItem(state,index){
			let id = state.list[index].cart_id
			let i = state.selectedList.indexOf(id)
			// 之前是选中，取消选中 
			if (i > -1) {
				// 取消当前商品选中状态
				state.list[index].checked = false
				// 移除选中列表中的当前商品
				return state.selectedList.splice(i,1)
			}
			// 选中
			state.list[index].checked = true
			state.selectedList.push(id)
		},
		// 全选
		selectAll(state){
			state.selectedList = state.list.map(v=>{
				// 设置选中状态
				v.checked = true
				return v.cart_id
			})
		},
		// 取消全选
		unSelectAll(state){
			state.list.forEach(v=>{
				// 设置选中状态
				v.checked = false
			})
			state.selectedList = []
		},
		// 删除选中
		delGoods(state){
			state.list = state.list.filter(v=>{
				return state.selectedList.indexOf(v.cart_id) === -1
			})
			
		},
		// 初始化popupIndex
		initPopupIndex(state,index){
			state.popupIndex = index
		},
		// 加入购物车
		addGoodsToCart(state,goods){
			state.list.unshift(goods)
			
		},
		// 清空购物车
		clearCart(state){
			state.list = []
			state.selectedList = []
			
		}
	},
	actions:{
		doSelectAll({state,commit,getters}){
			getters.checkedAll ? commit('unSelectAll') : commit('selectAll')
		},
		doDelGoods({commit,state}){
			if(state.selectedList.length === 0){
				return uni.showToast({
					title: '请选择要删除的商品',
					icon: 'none'
				});
			}
			uni.showModal({
				content:'是否删除选中',
				cancelText:'取消',
				confirmText:'确定',
				success: (res) => {
					// if(res.confirm){
					// 	$H.post('/index/card/delCart',{
					// 		id:state.selectedList.join(',')
					// 	}).then(res=>{
					// 		commit('delGoods')
					// 		uni.showToast({
					// 			title:'删除成功'
					// 		})
					// 	})
						
					// }
					
				}
			})
			
		}
	}
}